<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" class="search-form">
      <el-form-item>
        <el-input
          v-model="queryParams.process_name"
          placeholder="请输入工序名称"
          clearable
          size="small"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-select v-model="queryParams.process_status" placeholder="请选择状态" clearable size="small">
          <el-option
            v-for="dict in statusOptions"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">查询</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 标题和操作按钮 -->
    <div class="title-container">
      <h4 class="title">工序管理</h4>
    </div>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDeletes"
        >批量删除</el-button>
      </el-col>
    </el-row>

    <!-- 工序表格 -->
    <el-table
      v-loading="loading"
      :data="processList"
      @selection-change="handleSelectionChange"
      border
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" prop="index" width="60">
        <template slot-scope="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="工序名称" align="center" prop="process_name" />
      <el-table-column label="工序编号" align="center" prop="process_code" />
      <el-table-column label="状态" align="center" prop="process_status">
        <template slot-scope="scope">
          <el-tag :type="scope.row.process_status == 0 ? 'danger' : 'success'">
            {{ scope.row.process_status == 0 ? '停用' : '启用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="工序说明" align="center" prop="process_description" :show-overflow-tooltip="true" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            class="blue-text"
          >编辑</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            class="red-text"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改工序对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
      <!-- 添加标签页 -->
      <el-tabs v-model="activeTab">
        <el-tab-pane label="基本信息" name="basic">
          <el-form ref="form" :model="form" :rules="rules" label-width="100px">
            <el-form-item label="工序名称" prop="process_name">
              <el-input v-model="form.process_name" placeholder="请输入工序名称" />
            </el-form-item>
            <el-form-item label="工序编号" prop="process_code">
              <el-input v-model="form.process_code" placeholder="请输入工序编号" :disabled="true">
                <el-button slot="append" icon="el-icon-refresh" @click="getProcessCode" v-if="!form.process_id">自动编号</el-button>
              </el-input>
            </el-form-item>
            <el-form-item label="状态" prop="process_status">
              <el-radio-group v-model="form.process_status">
                <el-radio :label="1">启用</el-radio>
                <el-radio :label="0">停用</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="工序说明" prop="process_description">
              <el-input v-model="form.process_description" type="textarea" placeholder="请输入工序说明" />
            </el-form-item>
          </el-form>
        </el-tab-pane>

        <!-- 物料配件标签页 -->
        <el-tab-pane label="工位信息" name="process">
          <div class="process-container">
            <div class="process-header">
              <el-button type="primary" size="small" icon="el-icon-plus" @click="handleAddWorkstation">添加工位</el-button>
            </div>
            <!-- 工位表格 -->
            <el-table
              v-loading="workstationLoading"
              :data="workstationList"
              border
            >
              <el-table-column label="序号" align="center" width="60">
                <template slot-scope="scope">
                  {{ scope.$index + 1 }}
                </template>
              </el-table-column>
              <el-table-column label="工位名称" align="center" prop="station_name" />
              <el-table-column label="工位编号" align="center" prop="station_code" />
              <el-table-column label="工位说明" align="center" prop="remarks" :show-overflow-tooltip="true" />
              <el-table-column label="关联物料" align="center" width="100">
                <template slot-scope="scope">
                  <el-badge :value="getMaterialCount(scope.row.station_id)" :hidden="!getMaterialCount(scope.row.station_id)">
                    <el-button size="mini" type="info" plain round @click="viewStationMaterials(scope.row)">物料</el-button>
                  </el-badge>
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" width="150">
                <template slot-scope="scope">
                  <el-button size="mini" type="text" icon="el-icon-plus" @click="handleAddMaterialToStation(scope.row)" class="blue-text">添加物料</el-button>
                  <el-button size="mini" type="text" icon="el-icon-delete" @click="handleRemoveWorkstation(scope.row)" class="red-text">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <div class="empty-data" v-if="workstationList.length === 0">
              <div class="empty-icon">
                <i class="el-icon-document"></i>
              </div>
              <div class="empty-text">暂无数据</div>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
      
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
    
    <!-- 工位选择对话框 -->
    <el-dialog title="选择工位" :visible.sync="workstationSelectVisible" width="800px" append-to-body>
      <el-form :model="stationQuery" ref="stationQueryForm" :inline="true">
        <el-form-item label="工位名称">
          <el-input v-model="stationQuery.station_name" placeholder="请输入工位名称" clearable size="small" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="small" @click="searchWorkstations">搜索</el-button>
          <el-button icon="el-icon-refresh" size="small" @click="resetStationQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table
        v-loading="workstationSelectLoading"
        :data="workstationSelectList"
        border
        @selection-change="handleWorkstationSelectChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="工位名称" align="center" prop="station_name" :show-overflow-tooltip="true" />
        <el-table-column label="工位编号" align="center" prop="station_code" width="120" />
        <el-table-column label="工位说明" align="center" prop="remarks" :show-overflow-tooltip="true" />
      </el-table>
      <pagination
        v-show="stationSelectTotal > 0"
        :total="stationSelectTotal"
        :page.sync="stationQuery.pageNum"
        :limit.sync="stationQuery.pageSize"
        @pagination="getWorkstationList"
      />
      <div slot="footer" class="dialog-footer">
        <el-button @click="workstationSelectVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmSelectWorkstation">确定</el-button>
      </div>
    </el-dialog>
    
    <!-- 物料选择对话框 -->
    <el-dialog title="选择物料" :visible.sync="materialSelectVisible" width="800px" append-to-body>
      <el-form :model="materialQuery" ref="materialQueryForm" :inline="true">
        <el-form-item label="物料名称">
          <el-input v-model="materialQuery.material_name" placeholder="请输入物料名称" clearable size="small" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="small" @click="searchMaterials">搜索</el-button>
          <el-button icon="el-icon-refresh" size="small" @click="resetMaterialQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table
        v-loading="materialSelectLoading"
        :data="materialSelectList"
        border
        @selection-change="handleMaterialSelectChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="物料名称" align="center" prop="material_name" :show-overflow-tooltip="true" />
        <el-table-column label="物料编号" align="center" prop="material_code" width="120" />
        <el-table-column label="规格型号" align="center" prop="material_sfn" width="120" />
        <el-table-column label="单位" align="center" prop="material_unit" width="80" />
      </el-table>
      <pagination
        v-show="materialSelectTotal > 0"
        :total="materialSelectTotal"
        :page.sync="materialQuery.pageNum"
        :limit.sync="materialQuery.pageSize"
        @pagination="getMaterialList"
      />
      <div slot="footer" class="dialog-footer">
        <el-button @click="materialSelectVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmSelectMaterial">确定</el-button>
      </div>
    </el-dialog>
    
    <!-- 工位物料查看对话框 -->
    <el-dialog title="工位关联物料" :visible.sync="viewStationMaterialsVisible" width="800px" append-to-body>
      <div v-if="currentStation" class="station-info">
        <div class="station-name">工位名称：{{ currentStation.station_name }}</div>
        <div class="station-code">工位编号：{{ currentStation.station_code }}</div>
      </div>
      <el-table
        v-loading="false"
        :data="currentStationMaterials"
        border
      >
        <el-table-column label="序号" align="center" width="60">
          <template slot-scope="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column label="物料名称" align="center" prop="material_name" :show-overflow-tooltip="true" />
        <el-table-column label="物料编号" align="center" prop="material_code" width="120" />
        <el-table-column label="规格型号" align="center" prop="material_sfn" width="120" />
        <el-table-column label="单位" align="center" prop="material_unit" width="80" />
        <el-table-column label="操作" align="center" width="80">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-delete" @click="handleRemoveMaterial(scope.row)" class="red-text">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div v-if="currentStationMaterials.length === 0" class="empty-data">
        <div class="empty-icon">
          <i class="el-icon-document"></i>
        </div>
        <div class="empty-text">该工位暂无关联物料</div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="viewStationMaterialsVisible = false">关闭</el-button>
        <el-button type="primary" @click="handleAddMoreMaterials">添加物料</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listProcess, delProcess, addProcess, updateProcess, delProcessBatch, getProcessDetail } from "@/api/sc/process";
import { listWorkstation } from "@/api/basic/factory";
import { listMaterial } from "@/api/basic/material";
import { getAutoNumbers, getAutoNumbersConsume } from "@/api/basic/numbers";

export default {
  name: "ScProcess",
  data() {
    return {
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 工序表格数据
      processList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 状态选项
      statusOptions: [
        {
          value: 1,
          label: "启用"
        },
        {
          value: 0,
          label: "停用"
        }
      ],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        process_name: undefined,
        process_status: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        process_name: [
          { required: true, message: "工序名称不能为空", trigger: "blur" }
        ],
        process_code: [
          { required: true, message: "工序编号不能为空", trigger: "blur" }
        ],
        process_status: [
          { required: true, message: "状态不能为空", trigger: "change" }
        ]
      },
      // 标签页
      activeTab: 'basic',
      // 工位信息
      workstationLoading: false,
      workstationList: [],
      workstationIds: [],
      // 工位选择
      workstationSelectVisible: false,
      workstationSelectLoading: false,
      workstationSelectList: [],
      stationSelectTotal: 0,
      stationQuery: {
        pageNum: 1,
        pageSize: 10,
        station_name: undefined
      },
      // 物料选择
      materialSelectVisible: false,
      materialSelectLoading: false,
      materialSelectList: [],
      materialSelectTotal: 0,
      materialQuery: {
        pageNum: 1,
        pageSize: 10,
        material_name: undefined
      },
      // 当前选中的工位ID（用于添加物料）
      currentStationId: null,
      // 工位物料关联关系 { station_id: [material1, material2, ...] }
      stationMaterials: {},
      // 已选择的物料IDs
      selectedMaterialIds: [],
      // 工位物料查看对话框
      viewStationMaterialsVisible: false,
      currentStation: null,
      currentStationMaterials: []
    };
  },
  created() {
    this.getList();
  },
  watch: {
    // 监听路由变化，页面重新加载时刷新数据
    '$route'(to) {
      if (to.path === '/sc/process' || to.name === 'ScProcess') {
        console.log('工艺路线页面路由变化，刷新数据');
        this.getList();
      }
    },
    // 监听查询参数变化
    queryParams: {
      handler(newVal, oldVal) {
        if (oldVal && JSON.stringify(newVal) !== JSON.stringify(oldVal)) {
          console.log('工艺路线查询参数变化，刷新数据');
          this.getList();
        }
      },
      deep: true
    }
  },
  methods: {
    /** 查询工序列表 */
    getList() {
      this.loading = true;
      listProcess(this.queryParams).then(response => {
        if (response && response.rows) {
          console.log("获取的工序数据：", response.rows);
          this.processList = response.rows;
          this.total = response.total;
        } else {
          this.processList = [];
          this.total = 0;
          console.error("获取工序列表失败：", response);
        }
        this.loading = false;
      }).catch(error => {
        console.error("获取工序列表异常：", error);
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        process_id: undefined,
        process_name: undefined,
        process_code: undefined,
        process_status: 1,
        process_description: undefined
      };
      // 清空工位数据
      this.workstationList = [];
      this.workstationIds = [];
      // 清空工位-物料关联
      this.stationMaterials = {};
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      // 手动清空工序名称和状态选择
      this.queryParams.process_name = undefined;
      this.queryParams.process_status = undefined;
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.process_id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加工序";
      this.activeTab = 'basic'; // 默认打开基本信息标签
      // 不再自动获取工序编号，改为点击按钮时获取
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const processId = row.process_id || this.ids[0];
      
      console.log("正在获取工序详情，ID:", processId);
      
      // 使用processId构建query对象
      const query = { process_id: processId };
      
      // 先使用listProcess获取基本信息
      listProcess(query).then(response => {
        console.log("获取工序基本信息响应:", response);
        
        if (response && response.code === 200 && response.rows && response.rows.length > 0) {
          // 从列表结果中找到对应ID的工序
          const processInfo = response.rows.find(item => item.process_id === processId);
          
          if (processInfo) {
            console.log("获取到的工序基本信息:", processInfo);
            
            // 设置表单数据
            this.form = {
              process_id: processInfo.process_id,
              process_name: processInfo.process_name || '',
              process_code: processInfo.process_code || '',
              process_status: parseInt(processInfo.process_status || '1'),
              process_description: processInfo.process_description || processInfo.remarks || ''
            };
            
            console.log("设置到表单的数据:", this.form);
            
            // 获取工序详情（工位和物料关联信息）
            getProcessDetail(processId).then(detailResponse => {
              console.log("获取工序详情响应:", detailResponse);
              
              if (detailResponse && detailResponse.code === 200 && detailResponse.rows) {
                const rows = detailResponse.rows;
                
                // 检查第一行数据中的所有属性
                if (rows.length > 0) {
                  const firstRow = rows[0];
                  console.log("第一行数据所有属性：", Object.keys(firstRow));
                  
                  // 检查remarks字段在返回的行中是否有值
                  let hasRemarksValues = false;
                  rows.some(row => {
                    if (row.remarks) {
                      hasRemarksValues = true;
                      console.log("找到非空的remarks值:", row.remarks);
                      return true;
                    }
                    return false;
                  });
                  
                  if (!hasRemarksValues) {
                    console.warn("警告: 未找到任何非空的remarks值，可能需要检查后端SQL返回");
                  }
                }
                
                // 尝试获取原始SQL结果
                let sqlResult = null;
                if (detailResponse._raw) {
                  sqlResult = detailResponse._raw;
                  console.log("获取到原始SQL结果:", sqlResult);
                }
                
                // 添加辅助方法提取字段值
                const getFieldValueSafely = (row, fieldNames) => {
                  if (!row) return '';
                  
                  // 如果传入的是数组，按顺序尝试各个字段名
                  if (Array.isArray(fieldNames)) {
                    for (const name of fieldNames) {
                      if (row[name] !== null && row[name] !== undefined) {
                        return row[name];
                      }
                    }
                    return ''; // 所有字段名都没找到有效值
                  }
                  
                  // 如果是单个字段名
                  return (row[fieldNames] !== null && row[fieldNames] !== undefined) ? row[fieldNames] : '';
                };
                
                // 处理行数据，提取工位remarks
                const getStationRemarks = (row) => {
                  // 根据图片SQL结果，工位remarks字段在SQL结果的第3个remarks位置
                  // 由于JS对象会合并同名属性，我们需要使用特殊方法提取
                  
                  // 检查是否有多个备注字段（因为SQL结果中有多个同名字段）
                  // 从图片中可以看到，工位的remarks出现在SQL结果的后半部分
                  let stationRemark = '';
                  
                  // 1. 先检查明确命名的工位说明字段
                  const stationSpecificFields = [
                    'station_remarks', 
                    'station_remark', 
                    'station_description'
                  ];
                  stationRemark = getFieldValueSafely(row, stationSpecificFields);
                  if (stationRemark) return stationRemark;
                  
                  // 2. 检查第3个remarks字段
                  // 说明：从SQL结果看，这是第46列左右，与工位相关
                  const allFields = Object.keys(row);
                  const allValues = Object.values(row);
                  const remarksIndices = allFields.map((field, idx) => 
                    field === 'remarks' ? idx : -1).filter(idx => idx !== -1);
                  
                  // 如果找到了多个remarks字段
                  if (remarksIndices.length >= 3) {
                    // 尝试获取第3个或最后一个remarks的值
                    const targetIndex = remarksIndices.length >= 3 ? 
                      remarksIndices[2] : remarksIndices[remarksIndices.length - 1];
                    
                    if (targetIndex !== -1 && allValues[targetIndex] !== null && 
                        allValues[targetIndex] !== undefined) {
                      return allValues[targetIndex];
                    }
                  }
                  
                  // 3. 回退到普通的remarks字段
                  return row.remarks || '';
                };
                
                // 提取工位信息
                const workstationMap = new Map();
                const materialMap = new Map();
                this.stationMaterials = {};
                
                // 遍历所有行寻找工位和物料信息
                rows.forEach(row => {
                  if (!row) return;
                  
                  // 如果行包含工位ID，处理工位信息
                  if (row.station_id) {
                    const stationId = row.station_id;
                    
                    // 获取工位说明
                    const stationRemarks = getStationRemarks(row);
                    console.log(`工位(${row.station_name})的说明:`, stationRemarks);
                    
                    // 保存唯一工位
                    if (!workstationMap.has(stationId)) {
                      workstationMap.set(stationId, {
                        station_id: stationId,
                        station_name: row.station_name || '',
                        station_code: row.station_code || '',
                        remarks: stationRemarks
                      });
                    }
                    
                    // 如果行同时包含物料ID，处理物料信息
                    if (row.material_id) {
                      const materialId = row.material_id;
                      
                      // 初始化工位的物料数组
                      if (!this.stationMaterials[stationId]) {
                        this.$set(this.stationMaterials, stationId, []);
                      }
                      
                      // 避免重复添加物料
                      const key = `${stationId}-${materialId}`;
                      if (!materialMap.has(key)) {
                        materialMap.set(key, true);
                        
                        this.stationMaterials[stationId].push({
                          material_id: materialId,
                          material_name: row.material_name || '',
                          material_code: row.material_code || '',
                          material_sfn: row.material_sfn || '',
                          material_unit: row.material_unit || ''
                        });
                      }
                    }
                  }
                });
                
                // 更新工位列表
                this.workstationList = Array.from(workstationMap.values());
                
                // 确保工位说明字段可用
                this.workstationList = this.workstationList.map(station => {
                  // 如果remarks为空，再次尝试从原始数据中找出正确的说明
                  if (!station.remarks) {
                    // 查找对应station_id的原始行数据
                    const originalRows = rows.filter(r => r.station_id === station.station_id);
                    for (const r of originalRows) {
                      // 再次检查所有可能的字段
                      if (r.station_remark) station.remarks = r.station_remark;
                      else if (r.station_remarks) station.remarks = r.station_remarks;
                      else if (r.station_description) station.remarks = r.station_description;
                      
                      // 如果找到了说明，退出循环
                      if (station.remarks) break;
                    }
                  }
                  return station;
                });
                
                console.log("解析后的工位列表:", this.workstationList);
                this.workstationList.forEach(item => {
                  console.log(`工位[${item.station_id}] ${item.station_name}的remarks:`, item.remarks);
                });
                console.log("解析后的工位-物料关联:", this.stationMaterials);
              } else {
                console.warn("获取工序详情失败或格式不符合预期:", detailResponse);
              }
            }).catch(detailError => {
              console.error("获取工序详情异常:", detailError);
            }).finally(() => {
              // 确保对话框在所有数据处理完成后打开
              this.$nextTick(() => {
                this.$forceUpdate();
        this.open = true;
        this.title = "修改工序";
                this.activeTab = 'basic';
              });
            });
          } else {
            this.$modal.msgError("未找到指定ID的工序信息");
          }
        } else {
          this.$modal.msgError("获取工序基本信息失败: " + (response ? response.msg : '未知错误'));
          
          // 尝试直接打开编辑窗口，可能只需要ID
          this.open = true;
          this.title = "修改工序";
          this.activeTab = 'basic';
        }
      }).catch(error => {
        console.error("获取工序基本信息异常:", error);
        this.$modal.msgError("获取工序基本信息失败: " + (error.message || '未知错误'));
      });
    },
    /** 提交按钮 */
    async submitForm() {
      this.$refs["form"].validate(async valid => {
        if (valid) {
          // 如果开启了自动编号，在提交前获取真正的编号
          if (this.form.autoGenerateCode && this.form.process_code) {
            try {
              const response = await getAutoNumbersConsume(30);
              if (typeof response === 'string') {
                this.form.process_code = response;
              } else if (response && response.msg) {
                this.form.process_code = response.msg;
              }
            } catch (error) {
              this.$message.error('获取最终工序编号失败');
              return;
            }
          }

          // 构建提交数据，包含基本信息和工位
          const submitData = {
            ...this.form,
            // 构造工序详情列表 (basicProcessdetailsList)
            basicProcessdetailsList: []
          };
          
          // 添加工位关联到工序详情列表
          if (this.workstationList.length > 0) {
            this.workstationList.forEach(item => {
              // 获取该工位关联的物料
              const materials = this.stationMaterials[item.station_id] || [];
              
              // 如果工位有关联物料，为每个物料创建一条记录
              if (materials.length > 0) {
                materials.forEach(material => {
                  submitData.basicProcessdetailsList.push({
                    station_id: item.station_id,
                    station_name: item.station_name,
                    station_code: item.station_code,
                    remarks: item.remarks,
                    material_id: material.material_id,
                    material_name: material.material_name,
                    material_code: material.material_code,
                    material_sfn: material.material_sfn,
                    material_unit: material.material_unit
                  });
                });
              } else {
                // 如果工位没有关联物料，仅添加工位信息
                submitData.basicProcessdetailsList.push({
              station_id: item.station_id,
              station_name: item.station_name,
              station_code: item.station_code,
              remarks: item.remarks
                });
              }
            });
          }
          
          console.log("提交数据:", submitData);
          
          if (this.form.process_id != undefined) {
            updateProcess(submitData).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addProcess(submitData).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const processIds = row.process_id || this.ids;
      this.$modal.confirm('是否确认删除工序编号为"' + processIds + '"的数据项？').then(() => {
        if (Array.isArray(processIds)) {
          return delProcessBatch(processIds.join(','));
        } else {
          return delProcess(processIds);
        }
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },

    // 批量删除
    handleDeletes() {
      if (this.ids.length === 0) {
        this.$modal.msgWarning("请先选择要删除的工序");
        return;
      }
      
      const processIds = this.ids;
      this.$modal.confirm('是否确认批量删除选中的' + processIds.length + '条工序数据？').then(() => {
        // 确保processIds是字符串，API需要以路径参数形式传递
        const idsString = processIds.join(',');
        console.log("准备批量删除的工序IDs:", idsString);
        return delProcessBatch(idsString);
      }).then(response => {
        // 检查API响应
        if (response && response.code === 200) {
          this.getList();
          this.$modal.msgSuccess("批量删除成功");
          // 清空选择
          this.ids = [];
          this.single = true;
          this.multiple = true;
        } else {
          this.$modal.msgError(response.msg || "批量删除失败");
        }
      }).catch(error => {
        console.error("批量删除出错:", error);
        this.$modal.msgError("批量删除失败: " + (error.message || "未知错误"));
      });
    },

    // 工位信息相关方法
    getWorkstationList() {
      this.workstationSelectLoading = true;
      listWorkstation(this.stationQuery).then(response => {
        if (response && response.rows) {
          this.workstationSelectList = response.rows;
          this.stationSelectTotal = response.total;
        } else {
          this.workstationSelectList = [];
          this.stationSelectTotal = 0;
        }
        this.workstationSelectLoading = false;
      }).catch(error => {
        console.error("获取工位列表异常：", error);
        this.workstationSelectLoading = false;
      });
    },
    searchWorkstations() {
      this.stationQuery.pageNum = 1;
      this.getWorkstationList();
    },
    resetStationQuery() {
      this.stationQuery = {
        pageNum: 1,
        pageSize: 10,
        station_name: undefined
      };
      this.searchWorkstations();
    },
    handleWorkstationSelectChange(selection) {
      this.workstationIds = selection.map(item => item.station_id);
    },
    // 获取自动编号
    getProcessCode() {
      getAutoNumbers(30).then(response => {
        console.log("获取自动编号响应：", response);
        
        // 检查各种可能的返回格式
        if (typeof response === 'string') {
          // 直接返回字符串编号
          this.form.process_code = response;
          return;
        }
        
        if (response === null || response === undefined) {
          this.$modal.msgError("获取自动编号失败：返回为空");
          return;
        }
        
        // 检查常见的接口返回格式
        if (response.code === 200 || response.code === 0) {
          // 标准若依框架返回格式
          if (response.data) {
            this.form.process_code = response.data;
          } else if (response.msg && typeof response.msg === 'string') {
            this.form.process_code = response.msg;
          } else if (response.rows && response.rows.length > 0) {
            this.form.process_code = response.rows[0];
          } else {
            // 无法从标准字段获取，尝试直接读取
            console.warn("无法从标准返回字段获取编号，尝试直接读取response");
            this.form.process_code = "GXBH" + new Date().getTime(); // 生成临时编号
          }
        } else {
          console.error("获取自动编号失败，响应：", response);
          this.$modal.msgError("获取自动编号失败：" + (response.msg || "未知错误"));
        }
      }).catch(error => {
        console.error("获取自动编号异常：", error);
        this.$modal.msgError("获取自动编号异常");
      });
    },
    confirmSelectWorkstation() {
      if (this.workstationIds.length === 0) {
        this.$modal.msgError("请选择要添加的工位");
        return;
      }
      // 添加选中的工位到工序的工位列表中
      const selectedWorkstations = this.workstationSelectList.filter(item => this.workstationIds.includes(item.station_id));
      this.workstationList = [...this.workstationList, ...selectedWorkstations.filter(item => 
        this.workstationList.every(w => w.station_id !== item.station_id)
      )];
      this.workstationSelectVisible = false;
      this.$modal.msgSuccess("添加成功");
    },
    handleAddWorkstation() {
      this.workstationSelectVisible = true;
      this.activeTab = 'process'; // 切换到工位信息标签
      this.getWorkstationList(); // 获取工位列表
    },
    handleRemoveWorkstation(row) {
      this.$modal.confirm('是否确认删除该工位？').then(() => {
        const index = this.workstationList.findIndex(item => item.station_id === row.station_id);
        if (index !== -1) {
          this.workstationList.splice(index, 1);
          // 同时删除该工位的物料关联
          if (this.stationMaterials[row.station_id]) {
            this.$delete(this.stationMaterials, row.station_id);
          }
          this.$modal.msgSuccess("删除成功");
        }
      });
    },
    
    // 添加物料到工位
    handleAddMaterialToStation(row) {
      // 保存当前选中的工位ID
      this.currentStationId = row.station_id;
      // 打开物料选择对话框
      this.materialSelectVisible = true;
      // 获取物料列表
      this.getMaterialList();
    },
    
    // 获取物料列表
    getMaterialList() {
      this.materialSelectLoading = true;
      listMaterial(this.materialQuery).then(response => {
        if (response && response.rows) {
          this.materialSelectList = response.rows;
          this.materialSelectTotal = response.total;
        } else {
          this.materialSelectList = [];
          this.materialSelectTotal = 0;
        }
        this.materialSelectLoading = false;
      }).catch(error => {
        console.error("获取物料列表异常：", error);
        this.materialSelectLoading = false;
      });
    },
    
    // 搜索物料
    searchMaterials() {
      this.materialQuery.pageNum = 1;
      this.getMaterialList();
    },
    
    // 重置物料查询条件
    resetMaterialQuery() {
      this.materialQuery = {
        pageNum: 1,
        pageSize: 10,
        material_name: undefined
      };
      this.getMaterialList();
    },
    
    // 物料选择变更
    handleMaterialSelectChange(selection) {
      this.selectedMaterialIds = selection.map(item => item.material_id);
    },
    
    // 确认选择物料
    confirmSelectMaterial() {
      if (this.selectedMaterialIds.length === 0) {
        this.$modal.msgError("请选择要添加的物料");
        return;
      }
      
      // 获取选中的物料对象
      const selectedMaterials = this.materialSelectList.filter(
        item => this.selectedMaterialIds.includes(item.material_id)
      );
      
      // 确定当前要添加物料的工位ID
      let targetStationId = this.currentStationId;
      
      // 如果是从工位物料查看对话框打开的，使用currentStation的ID
      if (this.viewStationMaterialsVisible && this.currentStation) {
        targetStationId = this.currentStation.station_id;
      }
      
      if (!targetStationId) {
        this.$modal.msgError("未选择工位，无法添加物料");
        return;
      }
      
      // 初始化当前工位的物料数组（如果不存在）
      if (!this.stationMaterials[targetStationId]) {
        this.$set(this.stationMaterials, targetStationId, []);
      }
      
      // 添加选中的物料到当前工位的物料列表中（避免重复添加）
      selectedMaterials.forEach(material => {
        if (!this.stationMaterials[targetStationId].some(m => m.material_id === material.material_id)) {
          this.stationMaterials[targetStationId].push(material);
        }
      });
      
      // 如果是从工位物料查看对话框打开的，更新currentStationMaterials
      if (this.viewStationMaterialsVisible && this.currentStation) {
        this.currentStationMaterials = this.stationMaterials[targetStationId];
      }
      
      this.materialSelectVisible = false;
      this.$modal.msgSuccess(`成功为工位添加${selectedMaterials.length}种物料`);
      
      // 清空已选择的物料IDs
      this.selectedMaterialIds = [];
    },

    // 获取工位关联的物料数量
    getMaterialCount(stationId) {
      return this.stationMaterials[stationId] ? this.stationMaterials[stationId].length : 0;
    },

    // 查看工位关联的物料
    viewStationMaterials(row) {
      this.currentStation = row;
      this.currentStationMaterials = this.stationMaterials[row.station_id] || [];
      this.viewStationMaterialsVisible = true;
    },

    // 添加更多物料到当前工位
    handleAddMoreMaterials() {
      if (!this.currentStation) {
        this.$modal.msgError("请先选择一个工位");
        return;
      }
      this.materialSelectVisible = true;
      this.materialQuery.material_name = undefined; // 清空物料名称，以便搜索所有物料
      this.getMaterialList();
    },

    // 从当前工位移除物料
    handleRemoveMaterial(row) {
      this.$modal.confirm(`是否确认从工位 "${this.currentStation.station_name}" 移除物料 "${row.material_name}"？`).then(() => {
        const index = this.stationMaterials[this.currentStation.station_id].findIndex(item => item.material_id === row.material_id);
        if (index !== -1) {
          this.stationMaterials[this.currentStation.station_id].splice(index, 1);
          this.$modal.msgSuccess("移除成功");
        }
      });
    }
  }
};
</script>

<style scoped>
.search-form {
  padding: 15px;
  background: #fff;
  border-radius: 5px;
  margin-bottom: 20px;
}

.title-container {
  margin-bottom: 15px;
}

.title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  padding-left: 10px;
  border-left: 4px solid #409EFF;
}

.mb8 {
  margin-bottom: 8px;
}

.blue-text {
  color: #409EFF;
}

.red-text {
  color: #F56C6C;
}

.material-container {
  padding: 15px;
  background: #f5f7fa;
  border-radius: 5px;
  margin-top: 10px;
}

.material-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.process-container {
  padding: 15px;
  background: #f5f7fa;
  border-radius: 5px;
  margin-top: 10px;
}

.process-header {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 10px;
}

.empty-data {
  text-align: center;
  padding: 50px 0;
  color: #909399;
}

.empty-icon {
  font-size: 60px;
  margin-bottom: 10px;
}

.empty-text {
  font-size: 16px;
}
</style>